<template>
  <div>
    <div class="login">
      <el-row>
        <el-col :span="6" :offset="9">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>XXXX</span>
            </div>
            <el-form :model="loginData" status-icon :rules="rules" ref="loginData"
                     label-width="80px">
              <el-form-item label="用户名" prop="username">
                <el-input type="text" v-model="loginData.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginData.password"
                          autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="login">提交</el-button>
                <el-button @click="resetForm('loginData')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      const validateUsername = (rule, value, callback) => {
        const reg = /^[a-z]+[a-z0-9]{4,16}$/;
        if (!reg.test(value)) {
          callback(new Error('用户名不合法!'));
        } else {
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        const reg = /^[a-zA-Z0-9_~!@#$%^&*()\-,.+=;:'"`\[\]{}?/><\\]{3,16}$/;
        if (!reg.test(value)) {
          callback(new Error('密码不合法!'));
        } else {
          callback();
        }
      };
      return {
        loginData: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            {validator: validateUsername, trigger: 'blur'}
          ],
          password: [
            {validator: validatePassword, trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      login: function () {
        console.info(JSON.stringify(this.loginData));
        this.$http.post('login', JSON.stringify(this.loginData)).then(response => {
          console.log(response.body);
          if (null != response.body.data) {
            //登陆成功
            console.info("登陆成功");
            this.$router.push({path: '/home'});
          } else {
            console.info("登陆失败");
            this.$router.push({path: '/'});
          }
        }, response => {
          // error callback
        });
      },
      resetForm: function (formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped lang="scss">
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }

  .login {
    margin-top: 300px;
  }
</style>